package com.dic.mall.product.exception;

import com.dic.common.exception.BizCodeEnum;
import com.dic.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：leeliang
 * @date ：Created in 2020/11/8 15:28
 * @description：异常的统一处理
 * @modified By：
 * @version: 1.0$
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.dic.mall.product.controller")
public class MallExceptionControllerAdvice {

    @ExceptionHandler(value= MethodArgumentNotValidException.class)
    public R validException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
       Map hashMap = new HashMap<>();
        if(bindingResult.hasErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError:fieldErrors
                 ) {
                hashMap.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
        }
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMessage()).put("errors",hashMap);
    }

/*    @ExceptionHandler(value = Exception.class)
    public R handleException(Throwable th){
        System.out.println(th);
        System.out.println(th.fillInStackTrace());
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMessage());
    }*/
}
